import { Response } from 'express';
import { AuthenticatedRequest } from '@/middleware/auth';
import { Expense } from '@/models/Expense';
import { Income } from '@/models/Income';
import { FuelRecord } from '@/models/FuelRecord';

/**
 * @swagger
 * /api/statistics/expense:
 *   get:
 *     summary: 费用统计（月、季度、年）
 *     tags: [统计]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: vehicleId
 *         schema:
 *           type: string
 *         description: 车辆ID
 *       - in: query
 *         name: type
 *         schema:
 *           type: string
 *         description: 费用类型
 *       - in: query
 *         name: startDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 开始日期
 *       - in: query
 *         name: endDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 结束日期
 *     responses:
 *       200:
 *         description: 获取成功
 */
export const expenseStatistics = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { vehicleId, type, startDate, endDate } = req.query;
    const filter: any = { userId: req.userId };
    if (vehicleId) filter.vehicleId = vehicleId;
    if (type) filter.type = type;
    if (startDate || endDate) {
      filter.date = {};
      if (startDate) filter.date.$gte = new Date(startDate as string);
      if (endDate) filter.date.$lte = new Date(endDate as string);
    }
    const expenses = await Expense.find(filter);
    const total = expenses.reduce((sum, e) => sum + (e.totalAmount || 0), 0);
    res.status(200).json({
      success: true,
      message: '费用统计成功',
      data: { total, count: expenses.length },
    });
  } catch (error) {
    res.status(500).json({ success: false, message: '服务器内部错误' });
  }
};

/**
 * @swagger
 * /api/statistics/income:
 *   get:
 *     summary: 收入统计（月、季度、年）
 *     tags: [统计]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: vehicleId
 *         schema:
 *           type: string
 *         description: 车辆ID
 *       - in: query
 *         name: type
 *         schema:
 *           type: string
 *         description: 收入类型
 *       - in: query
 *         name: startDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 开始日期
 *       - in: query
 *         name: endDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 结束日期
 *     responses:
 *       200:
 *         description: 获取成功
 */
export const incomeStatistics = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { vehicleId, type, startDate, endDate } = req.query;
    const filter: any = { userId: req.userId };
    if (vehicleId) filter.vehicleId = vehicleId;
    if (type) filter.type = type;
    if (startDate || endDate) {
      filter.date = {};
      if (startDate) filter.date.$gte = new Date(startDate as string);
      if (endDate) filter.date.$lte = new Date(endDate as string);
    }
    const incomes = await Income.find(filter);
    const total = incomes.reduce((sum, e) => sum + (e.amount || 0), 0);
    res.status(200).json({
      success: true,
      message: '收入统计成功',
      data: { total, count: incomes.length },
    });
  } catch (error) {
    res.status(500).json({ success: false, message: '服务器内部错误' });
  }
};

/**
 * @swagger
 * /api/statistics/fuel:
 *   get:
 *     summary: 油耗统计
 *     tags: [统计]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: vehicleId
 *         schema:
 *           type: string
 *         description: 车辆ID
 *       - in: query
 *         name: startDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 开始日期
 *       - in: query
 *         name: endDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 结束日期
 *     responses:
 *       200:
 *         description: 获取成功
 */
export const fuelStatistics = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { vehicleId, startDate, endDate } = req.query;
    if (!vehicleId) {
      res.status(400).json({ success: false, message: '缺少车辆ID' });
      return;
    }
    const filter: any = { vehicleId };
    if (startDate || endDate) {
      filter.date = {};
      if (startDate) filter.date.$gte = new Date(startDate as string);
      if (endDate) filter.date.$lte = new Date(endDate as string);
    }
    const records = await FuelRecord.find(filter).sort({ date: 1 });
    // 简单油耗统计：总加油量/总行驶里程
    let totalFuel = 0;
    let totalDistance = 0;
    let lastOdometer = null;
    for (const rec of records) {
      totalFuel += rec.quantity;
      if (lastOdometer !== null) {
        totalDistance += rec.odometer - lastOdometer;
      }
      lastOdometer = rec.odometer;
    }
    const avgFuelConsumption =
      totalDistance > 0 ? (totalFuel / totalDistance) * 100 : 0;
    res.status(200).json({
      success: true,
      message: '油耗统计成功',
      data: {
        totalFuel,
        totalDistance,
        avgFuelConsumption: Number(avgFuelConsumption.toFixed(2)),
      },
    });
  } catch (error) {
    res.status(500).json({ success: false, message: '服务器内部错误' });
  }
};

/**
 * @swagger
 * /api/statistics/expense-ratio:
 *   get:
 *     summary: 费用支付比例统计
 *     tags: [统计]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: vehicleId
 *         schema:
 *           type: string
 *         description: 车辆ID
 *       - in: query
 *         name: startDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 开始日期
 *       - in: query
 *         name: endDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 结束日期
 *     responses:
 *       200:
 *         description: 获取成功
 */
export const expenseRatioStatistics = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { vehicleId, startDate, endDate } = req.query;
    const filter: any = { userId: req.userId };
    if (vehicleId) filter.vehicleId = vehicleId;
    if (startDate || endDate) {
      filter.date = {};
      if (startDate) filter.date.$gte = new Date(startDate as string);
      if (endDate) filter.date.$lte = new Date(endDate as string);
    }
    const expenses = await Expense.find(filter);
    const typeMap: Record<string, number> = {};
    let total = 0;
    for (const e of expenses) {
      const amount = e.totalAmount || 0;
      typeMap[e.type] = (typeMap[e.type] || 0) + amount;
      total += amount;
    }
    const ratio = Object.fromEntries(
      Object.entries(typeMap).map(([k, v]) => [
        k,
        total > 0 ? Number(((v / total) * 100).toFixed(2)) : 0,
      ])
    );
    res.status(200).json({
      success: true,
      message: '费用比例统计成功',
      data: { ratio, total },
    });
  } catch (error) {
    res.status(500).json({ success: false, message: '服务器内部错误' });
  }
};
